package com.jiujia.game.sdk.base.util;


import com.jiujia.game.sdk.base.JGameContextManager;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * *************************************************
 * Class: GameConfigReader
 * Author: Jiujia
 * Time: 2025/4/30 17:00
 * Description: 用于配置文件ini读取工具类
 * *************************************************
 */
public class JGameConfigReader {

    public static String getValue(String configFileName, String section, String key) {
        Map<String, String> configMap = loadConfig(configFileName);
        String fullKey = section + "." + key;
        return configMap.get(fullKey);
    }


    private static Map<String, String> loadConfig(String configFileName) {
        Map<String, String> configMap = new HashMap<>();
        try (InputStream is = JGameContextManager.getContext().getAssets().open(configFileName);
             BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {

            String line;
            String currentSection = null;

            while ((line = reader.readLine()) != null) {
                line = line.trim();

                // 处理 section
                if (line.startsWith("[") && line.endsWith("]")) {
                    currentSection = line.substring(1, line.length() - 1);
                    continue;
                }

                // 处理 key=value
                if (line.contains("=")) {
                    String[] parts = line.split("=");
                    if (parts.length == 2) {
                        String key = parts[0].trim();
                        String value = parts[1].trim();

                        // 如果存在 section，将 key 存储为 section.key
                        if (currentSection != null) {
                            key = currentSection + "." + key;
                        }

                        configMap.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return configMap;
    }
}